define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'classes/notice/index',
                    add_url: 'classes/notice/add',
                    edit_url: 'classes/notice/edit',
                    del_url: 'classes/notice/del',
                    multi_url: 'classes/notice/multi',
                    dragsort_url: '',
                    table: 'classes_notice',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'classes_id',
                sortOrder: 'asc',
                columns: [
                    [
                        {checkbox: true},
                        {
                            field: 'classes_id',
                            title: __('Classes'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="classes/classes/index" data-field="title"',
                            operate: '=',
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'admin_id',
                            title: __('SchoolName'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="classes/school/index" data-primary-key="admin_id" data-field="school_name"',
                            operate: '=',
                            formatter: Table.api.formatter.search,
                            searchable: Config.isSuperAdmin
                        },
                        {field: 'id', sortable: true, title: __('Id')},
                        {field: 'title', sortable: true, title: __('Title'), width: '350px'},
                        {field: 'school.school_name', title: __('SchoolName'), searchable: false, visible: Config.isSuperAdmin && Config.authversion==2, formatter:function(value){ return value ?? '本部'; }},
                        {field: 'classes.title', sortable: true, title: __('Classes'), searchable: false},
                        {field: 'classes.realname', sortable: true, title: __('Teacher')},
                        {field: 'type', sortable: true, title: __('Type'), formatter: function (value, row, index) {
                                return value == 1 ? __('NeedView') : (value == 2 ? __('NeedConfirm') : __('NeedReply'));
                            }},
                        {field: 'status', title: __('Status'), searchList: {"1": __('显示'), "0": __('隐藏')}, formatter: Table.api.formatter.toggle},
                        {field: 'updatetime', sortable: true, title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'buttons',title: __('Hanlelist'), table: table,
                            buttons: [{
                                name: 'teachersclasses',
                                text: __('View'),
                                classname: 'btn btn-xs btn-success btn-dialog',
                                title: function (row) { return row.title; },
                                icon: 'fa fa-eye',
                                url: 'classes/notice/deallist?notice_id={ids}'
                            }],
                            formatter: Table.api.formatter.buttons
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
                search: true,
                commonSearch: true
            });

            $(".btn-info").click(()=>{
                Backend.api.addtabs('./classes/notice/templates?ref=addtabs', '通知模板', 'fa fa-th-large fa-fw');
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        deallist: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'classes/notice/dealList' + location.search,
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: '',
                }
            });

            var table = $("#table");
            //默认字段
            var columns = [
                {field: 'id', title: __('Id'), operate: false},
                {field: 'realname', title: __('Realname'), operate: false},
                {field: 'handle_text', title: __('Handle'), operate: false, formatter: function(value, row, index){
                        return value ? value : '<span class="text-red">未处理</span>';
                    }},
                {field: 'studentsnotice.familymember.callname', title: __('Parent'), operate: false},
                {field: 'studentsnotice.updatetime', title: __('Noticetime'), operate: false, formatter: Table.api.formatter.datetime},
                {field: 'studentsnotice.reply_text', title: __('Replytext')},
                {
                    field: 'buttons',title: __('Operate'), table: table,
                    buttons: [{
                        name: 'Operate',
                        text: __('查看'),
                        classname: 'btn btn-xs btn-success btn-dialog',
                        icon: 'fa fa-eye',
                        disable: function (row) {
                            //返回true时按钮显示,返回false隐藏
                            return !row['studentsnotice'];
                        },
                        url: 'classes/notice/replydetail?students_id={ids}' + location.search.replace('?','&')
                    }],
                    formatter: Table.api.formatter.buttons
                },
            ];

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: columns
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        templates: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'classes/notice/templates',
                    add_url: 'classes/notice/templatesadd',
                    edit_url: 'classes/notice/templatesedit',
                    del_url: 'classes/notice/templatesdel',
                    multi_url: '',
                    table: 'classes_noticetemplate',
                }
            });

            var table = $("#table");
            //默认字段
            var columns = [
                {field: 'id', title: __('TemplateId'), operate: false},
                {field: 'title', title: __('Title'), operate: false},
                {field: 'tag', title: __('Tag'), operate: false},
                {field: 'short_content', title: __('Content'), operate: false},
                {
                    field: 'operate',
                    title: __('Operate'),
                    table: table,
                    events: Table.api.events.operate,
                    formatter: Table.api.formatter.operate
                }
            ];

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: columns
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        templatesadd: function () {
            Controller.api.bindevent();
        },
        templatesedit: function () {
            Controller.api.bindevent();
        },
        replydetail: function(){
            $('.zoomify').on('click', function(e){
                layer.open({
                    title: '查看图片'
                    ,content: '<img style="width:100%;" src="' + e.currentTarget.dataset.url + '"/>',
                    area: ['90%', '90%'],
                    btn:[]
                });
            });
        },
        add: function () {
            schoolChange();
            /*if(Config.isSuperAdmin){
                schoolChange();
            }
            $("#c-admin_id").change(function(){
                $('#c-classes_id').selectPageClear();
                schoolChange();
            });*/
            /*$('.fachoose').each(function(){
                $(this).data('admin-id', $admin_id);
            });*/
            Controller.api.bindevent();
            typeChange();
            responseTypeChange();
        },
        edit: function () {
            if(Config.isSuperAdmin){
                schoolChange();
            }
            $("#c-admin_id").change(function(){
                $('#c-classes_id').selectPageClear();
                schoolChange();
            });
            Controller.api.bindevent();
            typeChange();
            responseTypeChange();
        },
        api: {
            bindevent: function () {
                // Form.api.bindevent($("form[role=form]"));
                Form.api.bindevent($("form[role=form]"), function () {

                });
                // 添加链接
                $("#plupload-link").on('click', function(e){
                    var open = layer.open({
                        type: 1,
                        title: '添加链接',
                        area: ['500px'],
                        content: '<div class="box-body">'+
                            '<div class="form-group">'+
                            '<label for="link-input">请输入链接</label>'+
                            '<input type="email" class="form-control" id="link-input" placeholder="链接">'+
                            '</div>'+
                            '<div class="box-footer">'+
                            '<button id="link-submit" class="btn btn-primary">提交</button>'+
                            '</div>'+
                            '</div>',
                        success: function(layero, index){
                            $("#link-submit").on('click', function(){
                                let url = $("#link-input").val();
                                Fast.api.ajax({
                                    url: 'classes/notice/getLink?url=' + encodeURIComponent(url),
                                },function (data, ret) {
                                    console.log(data, ret)
                                    if(ret.code == 1){
                                        var title = ret.msg.replace(',', '，');
                                        $("#p-links").html($("#p-links").html() + '<li class="col-xs-3"><a href="' + url + '" data-url="' + url + '" target="_blank" data-title="' + ret.msg + '" class="thumbnail"><img src="'+ Fast.api.fixurl('ajax/icon?suffix=url') + '" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>');
                                        // $('#c-links_title').val($('#c-links_title').val() == '' ? title : $('#c-links_title').val() + ',' + title);
                                        $('#c-links').val($('#c-links').val() == '' ? url : $('#c-links').val() + ',' + url);
                                        return false
                                    }
                                }, function(error, ret){
                                    console.log(ret)
                                });

                                //   console.log($('#plupload-link').html())
                                layer.close(open);
                            });
                        }
                    });
                });

                // 移除链接事件
                $(document.body).on("click", "#p-links" + " .btn-trash", function () {
                    let url = $(this).closest("li").find('a.thumbnail').attr('data-url');
                    let title = $(this).closest("li").find('a.thumbnail').attr('data-title');
                    $('#c-links').val($('#c-links').val().replace(url + ',', ''));
                    $('#c-links').val($('#c-links').val().replace(',' + url, ''));
                    $('#c-links').val($('#c-links').val().replace(url, ''));
                    // $('#c-links_title').val($('#c-links_title').val().replace(title + ',', ''));
                    // $('#c-links_title').val($('#c-links_title').val().replace(',' + title, ''));
                    // $('#c-links_title').val($('#c-links_title').val().replace(title, ''));
                    $(this).closest("li").remove();
                });

                // 绑定TAB事件
                $('.panel-heading a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

                    var field = $(this).closest("ul").data("field");
                    var value = $(this).data("value");
                    var options = table.bootstrapTable('getOptions');
                    options.pageNumber = 1;
                    options.queryParams = function (params) {
                        var filter = {};
                        if (value !== '') {
                            filter[field] = value;
                        }
                        params.filter = JSON.stringify(filter);
                        return params;
                    };
                    table.bootstrapTable('refresh', {});
                    return false;
                });
            }
        }
    };
    function schoolChange(){
        $("input[name='row[admin_id]']").trigger('change');
        $admin_id = $("#c-admin_id").val();
        $('.fachoose').each(function(){
            $(this).data('admin-id', $admin_id);
        });
        $("#c-classes_id").data("params", function(){
            $admin_id = $("#c-admin_id").val();

            return {"custom[admin_id]": $admin_id, "custom[status]": 'normal'};
        });
    }
    function typeChange(){
        $("input[name='row[type]']").trigger('change');
        $("input[name='row[type]']").change(function(){
            if($(this).val() == 2){
                $("#response_type").closest('.form-group').show();
                $("#issecret").closest('.form-group').show();
            }else{
                $("#response_type").closest('.form-group').hide();
                $("#issecret").closest('.form-group').hide();
            }
        });
    }
    function responseTypeChange(){
        $("input[name='row[response_type][]']").on('click', function(){
            let val = $(this).val();
            let isChecked = $(this).is(':checked');
            if(val == 0 && isChecked){
                $("input[name='row[response_type][]']").each(function(){
                    if($(this).val() != 0){
                        $(this).prop("checked",false);
                    }
                })
            }
            if(val != 0 && isChecked){
                $("input[name='row[response_type][]']").each(function(){
                    if($(this).val() == 0){
                        $(this).prop("checked",false);
                    }
                })
            }
        });
    }
    return Controller;
});